package com.fjb.controller.base;

import java.time.LocalDateTime;
import java.util.List;
import java.util.StringJoiner;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjb.common.entity.HttpCode;
import com.fjb.dto.LoginUserInfo;
import com.fjb.pojo.login.SysLoginToken;
import com.fjb.pojo.product.ProductAttributeSku;
import com.fjb.service.login.SysLoginTokenService;

/**
 * @Description:基础
 * @author hemiao
 * @time:2020年2月19日 下午6:33:06
 */
public class BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private SysLoginTokenService sysLoginTokenService;
	
	/**
	 * X-fjb-Token
	 */
	public static final String WX_TOKEN_ID= "X-fjb-Token";
	
	/**
	 * file_service_location 文件服务器地址
	 */
	public static final String FILE_SERVICE_LOCATION = "file_service_location";
	
	
	/**
	 * @Description:获得token 没有登陆就跳转登陆页面
	 * @param request
	 * @return
	 * UserInfo
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月4日 下午10:36:38
	 */
	public LoginUserInfo getBaseWxTokenId(HttpServletRequest request) {
		String appToken = request.getHeader(WX_TOKEN_ID);
		if(appToken==null) {
			throw new RuntimeException(HttpCode.NO_LOGIN.getMsg());
		}else {		
			LoginUserInfo userInfo = getBaseUserInfo(appToken);
			if(userInfo==null) {			
				throw new RuntimeException(HttpCode.NO_LOGIN.getMsg());
			}	
			return userInfo;
		}
	}
	
	/**
	 * @Description:可以不登录
	 * @param request
	 * @return
	 * LoginUserInfo
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月19日 下午6:28:22
	 */
	public LoginUserInfo getBaseWxTokenIdTwo(HttpServletRequest request) {
		String appToken = request.getHeader(WX_TOKEN_ID);
		if(appToken==null) {
			return null;
		}else {	
			StringJoiner sj = new StringJoiner(":");
			sj.add(WX_TOKEN_ID);
			sj.add(appToken);
			String token = sj.toString();
			// 从redis 中取
			//String userInfoStr = redisTemplate.opsForValue().get(token);
			// 从数据库中查询
			QueryWrapper<SysLoginToken> queryWrapper = new QueryWrapper<SysLoginToken>();
			queryWrapper.eq("token_id", token);
			SysLoginToken loginToken = sysLoginTokenService.getOne(queryWrapper);
			if(loginToken==null) {			
				throw new RuntimeException(HttpCode.NO_LOGIN.getMsg());
			}
			LocalDateTime failureTime = loginToken.getFailureTime();
			// 判断是否失效
			LocalDateTime localDateTime = LocalDateTime.now();
			// 比较  现在的时间 比 设定的时间 之前  返回的类型是Boolean类型
	        if(localDateTime.isAfter(failureTime)) {
	        	// 登陆已经过期  删除数据	
	        	sysLoginTokenService.remove(queryWrapper);
	        	logger.info(" 登录超时 : "+token);
	        	return null;
	        }			
			String userInfoStr = loginToken.getTokenContent();
			LoginUserInfo userInfo = JSON.parseObject(userInfoStr, LoginUserInfo.class);
			return userInfo;
		}
	}
	
	/**
	 * @Description:用token取用户信息
	 * @param appToken
	 * @return
	 * LoginUserInfo
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月4日 下午11:28:42
	 */
	public LoginUserInfo getBaseUserInfo(String appToken) {
		StringJoiner sj = new StringJoiner(":");
		sj.add(WX_TOKEN_ID);
		sj.add(appToken);
		String token = sj.toString();
		// 从redis 中取
		//String userInfoStr = redisTemplate.opsForValue().get(token);
		// 从数据库中查询
		QueryWrapper<SysLoginToken> queryWrapper = new QueryWrapper<SysLoginToken>();
		queryWrapper.eq("token_id", token);
		SysLoginToken loginToken = sysLoginTokenService.getOne(queryWrapper);
		if(loginToken==null) {			
			throw new RuntimeException(HttpCode.NO_LOGIN.getMsg());
		}
		LocalDateTime failureTime = loginToken.getFailureTime();
		// 判断是否失效
		LocalDateTime localDateTime = LocalDateTime.now();
		// 比较  现在的时间 比 设定的时间 之前  返回的类型是Boolean类型
        if(localDateTime.isAfter(failureTime)) {
        	// 登陆已经过期  删除数据	
        	sysLoginTokenService.remove(queryWrapper);
        	logger.info(" 登录超时 : "+token);
        	throw new RuntimeException(HttpCode.NO_LOGIN.getMsg());
        }		
		String userInfoStr = loginToken.getTokenContent();
		LoginUserInfo userInfo = JSON.parseObject(userInfoStr, LoginUserInfo.class);
		return userInfo;
	}
	
	/**
	 * @Description:存token
	 * @param wxOpenId
	 * @param userInfo
	 * @return
	 * String
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月4日 下午11:28:31
	 */
	public String setBaseWxTokenId(HttpServletRequest request,String wxOpenId,LoginUserInfo userInfo) {
		Integer userId = userInfo.getUserId();
		String appToken = userId + wxOpenId;	
		String token = WX_TOKEN_ID + ":" + appToken;
		String jsonStr = JSON.toJSONString(userInfo);
		// 存redis
		//redisTemplate.opsForValue().set(token, jsonStr,60*10*6*24*15,TimeUnit.SECONDS);
		// 存数据库	
		// 先删除	
		QueryWrapper<SysLoginToken> queryWrapper = new QueryWrapper<SysLoginToken>();
		queryWrapper.eq("token_id", token);
		queryWrapper.eq("user_id", userId);	
		sysLoginTokenService.remove(queryWrapper);
		// 再保存最新的
		SysLoginToken lt = new SysLoginToken();
		lt.setUserId(userId);
		lt.setTokenId(token);
		lt.setTokenContent(jsonStr);
		LocalDateTime startTime = LocalDateTime.now();
		lt.setStartTime(startTime);
		// 设置超时时间	
		LocalDateTime failureTime = startTime.plusDays(15);
		lt.setFailureTime(failureTime);
		sysLoginTokenService.save(lt);	
		logger.info(" 登录成功: "+token);
		return appToken;	
	}	
	
	/*public static void main(String[] args) {
		DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime startTime = LocalDateTime.now();
		System.out.println(dtf2.format(startTime));
		// 设置超时时间		
		LocalDateTime failureTime = startTime.plusDays(10);
		System.out.println(dtf2.format(failureTime));
		
		StringJoiner sj = new StringJoiner(":");
		sj.add(WX_TOKEN_ID);
		sj.add("123456");
		String token = sj.toString();
		System.out.println(token);	
	}*/
	
	/**
	 * @Description:根据  titleCode 和   attrCode  获得  sku 信息
	 * @param titleCode
	 * @param attrCode
	 * @param skuList
	 * @return
	 * ProductAttributeSku
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月1日 下午10:57:58
	 */
	public static ProductAttributeSku getBaseProductAttributeSku(String titleCode,String attrCodeOne, String attrCodeTwo,
			List<ProductAttributeSku> skuList,Integer attrLevel) {
		ProductAttributeSku skuVo = null;
		for (ProductAttributeSku sku : skuList) {
			String attrTitleCode = sku.getAttrTitleCode();
			String attrCodeOne2 = sku.getAttrCodeOne();	
			String attrCodeTwo2 = sku.getAttrCodeTwo();
			if(attrLevel.equals(1)) {		
				if(attrCodeOne.equals(attrCodeOne2)&&attrTitleCode.equals(titleCode)) {
					skuVo = sku;
					break;
				}			
			}else if (attrLevel.equals(2)) {
				if(attrCodeOne.equals(attrCodeOne2)&&attrCodeTwo.equals(attrCodeTwo2)&&attrTitleCode.equals(titleCode)) {
					skuVo = sku;
					break;
				}
			}
		}
		return skuVo;
	}
}
